/* jshint esversion: 6 */
const Router = require('koa-router');
const tool = require("../../tools/tool");
const router = new Router();
const {db, Op, QueryTypes} = require("../../models/db");
// 修改密码

router.post('/user/save', async ctx => {
    let formData = ctx.request.body.formData
    let tenantId = ctx.user.tenantId;
    if(formData.mobile) {
        let mobile = tool.xe.trim(formData.mobile)
        mobile = /^1[3-9][0-9]{9}$/.test(mobile)
        if(!mobile) return ctx.err('手机号码不正确')
    }
    let id = formData.id
    let username = tool.xe.trim(formData.username)
    let name = tool.xe.trim(formData.name)
    if(!username) return ctx.err('请输入用户名')
    if(!name) return ctx.err('请输入姓名')
    let mobile =tool.xe.trim(formData.mobile)
    let deptId =  formData.deptId
    let roleId =  formData.roleId
    let pinYin =  tool.py(formData.name)
    let userModel;
    if(id) {
        userModel = await db.models['admin'].findOne({
            where: {
                tenantId,
                id,
            }
        })
        if(!userModel) return ctx.err('没有找到用户')
        if(username !== userModel.username) {
            let has = await db.query(`select * from admin where tenantId=${tenantId} and username='${username}' `,{type: QueryTypes.SELECT, plain: true})
            if(has) return ctx.err('已存在相同的用户名')
        }
        if(userModel.name !== name) {
            let hasName =  await db.models['admin'].findOne({
                where: {
                    tenantId,
                    name
                }
            })
            if(hasName) return ctx.err('已存在相同姓名')
        }
        userModel.tenantId = tenantId;
        userModel.username = username;
        userModel.roleId = roleId;
        userModel.deptId = deptId;
        userModel.pinYin = pinYin;
        userModel.mobile = mobile;
        userModel.name = name;
        await userModel.save()
    }
    else {
        let has =  await db.models['admin'].findOne({
            where: {
                username,
            }
        })
        if(has) return ctx.err('已存在相同用户名,最好用手机号作用户名')
        let hasName =  await db.models['admin'].findOne({
            where: {
                tenantId,
                name
            }
        })
        if(hasName) return ctx.err('已存在相同姓名')

        userModel = db.models['admin'].build();
        userModel.token = tool.uuid();
        userModel.userpwd = tool.crypto.MD5('12321')
        userModel.username = username;
        userModel.tenantId = tenantId;
        userModel.roleId = roleId;
        userModel.deptId = deptId;
        userModel.pinYin = pinYin;
        userModel.mobile = mobile;
        userModel.name = name;
        await userModel.save()
    }
    return ctx.suc('保存成功')
})



module.exports = router;